package com.itheima.Jiuye13;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SiSuo {
    public static void main(String[] args) {
        //创建两个锁对象
        Lock locka = new ReentrantLock();
        Lock lockb = new ReentrantLock();
        //创建两个线程分别开启
        //将任务作为Thread类的构造方法
        new Thread(()->{
           while (true){
               if (locka.tryLock()) {     //判断能否获取a锁，能返回true，不能反悔false
                   try {
                       if (lockb.tryLock()){  //判断能否获取b锁，能返回true，不能反悔false
                           try {
                               System.out.println("先获取a锁......，再获取b锁.....");
                           } finally {        //被此关键字修饰除非停止虚拟机，不然都会执行它里面的代码
                               lockb.unlock();   //释放b锁
                           }
                       }
                   } finally {
                       locka.unlock();    //释放a锁
                   }
               }
           }
        }).start();
        new Thread(()->{
            while (true){
                if (lockb.tryLock()){   //判断能否获取b锁，能返回true,不能返回false
                    try {
                        if (locka.tryLock()){   //判断能否获取a锁，能返回true，不能返回false
                            try {
                                System.out.println("先获取bbbbbbb锁....，再获取aaaaaa锁.....");
                            } finally {
                                locka.unlock();   //释放a锁
                            }
                        }
                    } finally {
                        lockb.unlock();   //释放b锁
                    }
                }
            }
        }).start();
    }
}
